﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.PatientCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.PatientHandler
{
    /// <summary>
    /// 修改默认就诊人处理
    /// </summary>
    public class UpdatePatientHandler : IRequestHandler<UpdatePatientCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Patient> prep;
        private readonly ILogger<UpdatePatientHandler> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="prep">仓储</param>
        /// <param name="logger">日志</param>
        public UpdatePatientHandler(IBaseRepository<Patient> prep,ILogger<UpdatePatientHandler> logger)
        {
            this.prep = prep;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        public async Task<APIResult<object>> Handle(UpdatePatientCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
             
                
                    var list = prep.GetAll().Where(x => x.ParentId == request.ParentId);
                    foreach (var item in list)
                    {
                        item.IsDefault = false;
                      
                    }
                  var a=  prep.UpdateRang(list).Result;

              
               
                    if (a > 0)
                    {
                        result.Code = APIEnum.Success;
                        result.Msg = "修改成功";
                        logger.LogInformation(result.Msg);
                        result.Data = a;

                    }
                    else
                    {
                        result.Code = APIEnum.Failed;
                        result.Msg = "修改失败";
                        logger.LogError(result.Msg);
                        result.Data = a;

                    }
              
                return await Task.FromResult(result);

               

            }
            catch (Exception ex)
            {
                logger.LogError($"Error: {ex.Message}");
                throw;
            }
          
            
        }
    }
}
